package com.cnswhy.cloud.server.merchant.controller.customer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.common.core.base.controller.SuperController;
import com.cnswhy.cloud.common.core.base.request.PageParams;
import com.cnswhy.cloud.common.core.exception.BizException;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.service.IdGeneratorService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.enumeration.TransType;
import com.cnswhy.cloud.server.common.entity.enumeration.WalletType;
import com.cnswhy.cloud.server.common.entity.mq.TeamValueAddMsg;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.dao.CustomerMapper;
import com.cnswhy.cloud.server.core.dto.CustomerPageDTO;
import com.cnswhy.cloud.server.core.dto.CustomerSaveDTO;
import com.cnswhy.cloud.server.core.dto.CustomerUpdateDTO;
import com.cnswhy.cloud.server.core.entity.*;
import com.cnswhy.cloud.server.core.query.QueryGenerator;
import com.cnswhy.cloud.server.core.service.CustomerWalletService;
import com.cnswhy.cloud.server.core.service.WalletTransDtlService;
import com.cnswhy.cloud.server.core.service.customer.CustomerService;
import com.cnswhy.cloud.server.core.service.spell.SpellOrderService;
import com.cnswhy.cloud.server.core.utils.PasswordCoder;
import com.cnswhy.cloud.server.core.wallet.WalletService;
import com.cnswhy.cloud.server.merchant.dto.CustomerPasswordDTO;
import com.cnswhy.cloud.server.core.dto.CustomerTeamDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//import com.github.zuihou.security.annotation.PreAuth;


/**
 * <p>
 * 前端控制器
 * 
 * </p>
 *
 * @author cnswhy
 * @date 2020-10-16
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/customer")
@Api(value = "Customer", tags = "")
//@PreAuth(replace = "customer:")
public class CustomerController extends SuperController<CustomerService, Long, Customer, CustomerPageDTO, CustomerSaveDTO, CustomerUpdateDTO> {
    @Autowired
    CustomerWalletService customerWalletService;
    @Autowired
    WalletService walletService;
    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    WalletTransDtlService walletTransDtlService;
    @ApiOperation(value = "分页列表查询+账户")
    @PostMapping(value = "/teamPage")
    public R<IPage<CustomerTeam>> teamPage(@RequestBody @Validated PageParams<CustomerTeamDTO> params) {
        // 处理参数
        if(StringUtils.isNotBlank(params.getModel().getPromoterPhone())){
            Customer customer = baseService.getOne(Wraps.<Customer>lbQ().eq(Customer::getLoginName,params.getModel().getPromoterPhone()));
            if(customer == null){
                return fail("团队长手机号不存在");
            }
            params.getModel().setPromoterList(customer.getPromoterList());
            params.getModel().setUpPhone(customer.getPromoterMobile());
            params.getModel().setCurrLevel(customer.getPrimaryPromoterLevel());
        }

        IPage<CustomerTeam> page = params.buildPage();
        //query1(params, page, null);
        page = customerMapper.teamPage(page,params.getModel());
        return success(page);
    }
    @Override
    public R<Customer> handlerSave(CustomerSaveDTO model) {
        if(StringUtils.isNotBlank(model.getPromoterMobile())){
            Customer promoter = baseService.getOne(Wraps.<Customer>lbQ().eq(Customer::getLoginName,model.getPromoterMobile()));
            if(promoter == null){
                return R.fail("推荐人手机号不存在");
            }else{
                if(promoter.getPrimaryPromoterId() == null){
                    model.setPrimaryPromoterId(promoter.getId());
                    model.setPrimaryPromoterLevel(1L);
                    model.setPrimaryPromoterPhone(promoter.getLoginName());
                }else{
                    model.setPrimaryPromoterId(promoter.getPromoterId());
                    model.setPrimaryPromoterLevel(promoter.getPrimaryPromoterLevel() + 1);
                    model.setPrimaryPromoterPhone(promoter.getPrimaryPromoterPhone());
                }
            }
        }else{
            model.setPrimaryPromoterLevel(0L);
        }
        model.setStatus(2);
        return R.successDef();
    }

    @Override
    public R<Customer> handlerAfterSave(CustomerSaveDTO customerSaveDTO,Customer customer) {
        if(customer.getPromoterId() != null){
            Customer promoter = baseService.getById(customer.getPromoterId());
            customer.setPromoterList(promoter.getPromoterList()+ customer.getId());

        }else{
            if(StringUtils.isNotBlank(customer.getPromoterMobile())){
                Customer promoter = baseService.getOne(Wraps.<Customer>lbQ().eq(Customer::getLoginName,customer.getPromoterMobile()));
                if(promoter != null){
                    customer.setPromoterId(promoter.getId());
                    customer.setPromoterList(promoter.getPromoterList() + customer.getId());
                    baseService.updateById(customer);
                }
            }else{
                customer.setPromoterList(customer.getId()+"");
                baseService.updateById(customer);
            }
        }
        return R.successDef();
    }

    @GetMapping("repairPromoteList")
    public R<String> repairPromoteList(){
        List<Customer> customerList = baseService.list(Wraps.<Customer>lbQ().isNull(Customer::getPromoterId));
        for(Customer customer : customerList) {
            customer.setPrimaryPromoterLevel(0L);
            baseService.updateById(customer);
            repairSub(customer);
        }
        return success("成功");
    }


    private void repairSub(Customer customer){
        List<Customer> customerList = baseService.list(Wraps.<Customer>lbQ().eq(Customer::getPromoterId,customer.getId()));
        for(Customer customer1 : customerList){
            if(customer.getPrimaryPromoterId() == null){
                customer1.setPrimaryPromoterId(customer.getId());
                customer1.setPrimaryPromoterPhone(customer.getLoginName());
            }else{
                customer1.setPrimaryPromoterId(customer.getPrimaryPromoterId());
                customer1.setPrimaryPromoterPhone(customer.getPrimaryPromoterPhone());
            }
            customer1.setPrimaryPromoterLevel(customer.getPrimaryPromoterLevel() + 1);
            //customer1.setPromoterList(customer.getPromoterList() + customer1.getId());
            baseService.updateById(customer1);
            repairSub(customer1);
        }
    }
    @PostMapping("resetPassword")
    public R<Boolean> resetPassword(@RequestBody CustomerPasswordDTO customerPasswordDTO){
        Customer customer = baseService.getById(customerPasswordDTO.getId());
        if(customer != null){
            customer.setPassWord(PasswordCoder.generatePassword("123456"));
            baseService.updateById(customer);
        }
        return success();
    }

    @PostMapping("resetPayPassword")
    public R<Boolean> resetPayPassword(@RequestBody CustomerPasswordDTO customerPasswordDTO){
        Customer customer = baseService.getById(customerPasswordDTO.getId());
        if(customer != null){
            customer.setTradePass(PasswordCoder.generatePassword("123456"));
            baseService.updateById(customer);
        }
        return success();
    }
    @Autowired
    MessageService messageService;
    @Autowired
    IdGeneratorService idGeneratorService;
    @GetMapping("addTeamValue")
    public R<String> addTeamValue(String mobile){
        Customer customer = baseService.getOne(Wraps.<Customer>lbQ().eq(Customer::getLoginName, mobile));
        if(customer != null){
            messageService.sendQueueByObject(AmqpExchange.TEAM_VALUE_MESSAGE, TeamValueAddMsg.builder().id(customer.getId()).promoterId(customer.getPromoterId()).orderId(idGeneratorService.genCommonIdString()).build());
        }
        return R.successDef();
    }
    @Autowired
    CustomerService customerService;
    @Autowired
    SpellOrderService spellOrderService;
    @Autowired
    RedisService redisService;
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<Customer> customerList = list.stream().map((map) -> {
            Customer customer = Customer.builder().build();
            return customer;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(customerList));
    }
}
